


# to manipulate data
library(tidyverse)

# to load WDI data
library(WDI)

# to generate missingness map
library(visdat)

# for anti-aliasing (otherwise the figure will look blurry)
library(Cairo)


# load data
load("full_data_conditionality_covariates.RData")

# compare different debt indicators
compare_measures <- WDI(country = "all", indicator = c("GC.DOD.TOTL.GD.ZS","DT.TDS.DECT.GN.ZS",
                                                       "DT.DOD.DECT.GN.ZS","DT.TDS.DECT.EX.ZS"),
                start = 1980, end = 2019, extra = TRUE, cache = NULL) %>%
  filter(income!="Aggregates") %>%
  rename(central_gov_debt_perc_gdp = GC.DOD.TOTL.GD.ZS,
         total_debt_service_perc_gni = DT.TDS.DECT.GN.ZS,
         external_debt_stocks_perc_gni = DT.DOD.DECT.GN.ZS,
         total_debt_service_perc_exp = DT.TDS.DECT.EX.ZS) %>%
  filter(iso3c %in% full_df$iso3c) %>%
  filter(!(iso3c=="SSD" & year<2011) & !(iso3c=="TLS" & year < 2002) & !(iso3c=="NAM" & year<1990) &
           !(iso3c=="KAZ" & year<1991) & !(iso3c=="UZB" & year<1991) & !(iso3c=="TKM" & year<1991) & 
           !(iso3c=="AZE" & year<1991) & !(iso3c=="KGZ" & year<1991) &  !(iso3c=="UKR" & year<1991)) %>%
  select(central_gov_debt_perc_gdp, total_debt_service_perc_gni,
         external_debt_stocks_perc_gni, total_debt_service_perc_exp)
# GC.DOD.TOTL.GD.ZS           Central government debt, total (% of GDP)
# DT.TDS.DECT.GN.ZS           Total debt service (% of GNI)
# DT.DOD.DECT.GN.ZS           External debt stocks (% of GNI)
# DT.TDS.DECT.EX.ZS           Total debt service (% of exports of goods, services and primary income)

compare_measures %>%
  rename(`Central government debt, total (% of GDP)` = central_gov_debt_perc_gdp,
         `Total debt service (% of GNI)` = total_debt_service_perc_gni,
         `External debt stocks (% of GNI)` = external_debt_stocks_perc_gni,
         `Total debt service (% exports of goods, \nservices, and primary income)` = total_debt_service_perc_exp) %>%
  vis_miss(sort_miss = T, show_perc_col = F) +
  theme(plot.margin = unit(c(0,3.5,0,0.5), "cm"))

ggsave("figure6.png", width = 10, height = 7.5, type="cairo")
